//
//  MNDRegisterViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/4.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDRegisterViewController.h"
#import "MNDRegisterModel.h"
#import "MNDRegisterBottomView.h"
#import "MNDRegisterDefaultCell.h"
#import "MNDRegisterCaptchaCell.h"
#import "MNDLoginViewController.h"
#import "MNDWebViewController.h"
#import "UIButton+JKCountDown.h"
#import "NSString+JKNormalRegex.h"
#import "MNDRegisterRecommendCell.h"

#import <UMPush/UMessage.h>


@interface MNDRegisterViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) MNDRegisterModel *registerModel;

@property (weak, nonatomic) IBOutlet UIView *tableFooterView;

@property (weak, nonatomic) IBOutlet UIButton *registerBtn;

@property (weak, nonatomic) IBOutlet UIButton *protocolBtn;
@property (weak, nonatomic) IBOutlet UILabel *protocolLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recommandViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recommandeTopMargin;
@property (weak, nonatomic) IBOutlet UIView *bottomLineView;

@property(nonatomic, assign) BOOL showRecommend;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *footerVerticalConstraint;

@end

@implementation MNDRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviBarTranslucent = NO;
    self.registerModel = [MNDRegisterModel new];
    [self setupUI];
    [self initialLeftBarButtons];
    
    if (kScreenHeight >= 812) {
        self.tableFooterView.frame = CGRectMake(0, 0, kScreenWidth, 290);
    }
    
    self.tableView.tableFooterView = self.tableFooterView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}

- (void)setupUI{
    
}

- (void)initialLeftBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    if (self.presentingViewController) {
        //present方式
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            
        }];
    } else {
        //push方式
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)toLoginView:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    MNDLoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:[MNDLoginViewController description]];
    
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - UITableView Datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_showRecommend) {
        return 5;
    }else {
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    //验证码输入框
    if (indexPath.row == 1) {
        static NSString *const cellIdentifier = @"captchaCell";
        MNDRegisterCaptchaCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        cell.tipLabel.text = @"短信验证码";
        cell.tfInput.keyboardType = UIKeyboardTypeNumberPad;
        cell.captchaBtn.enabled = YES;
        RAC(self.registerModel, phoneCaptcha) = [cell.tfInput.rac_textSignal takeUntil:cell.rac_prepareForReuseSignal];
        RAC(cell.captchaBtn, enabled) = [[RACSignal combineLatest:@[RACObserve(self.registerModel, userPhone)] reduce:^id (NSString *phone){

            return @(phone.length >= 11);
        }] takeUntil:cell.rac_prepareForReuseSignal];
//        RAC(self, registerModel.phoneCaptcha) = [[RACSignal combineLatest:@[RACObserve(cell, tfInput.text)] reduce:^id (NSString *captcha){
//
//            return captcha;
//        }] takeUntil:cell.rac_prepareForReuseSignal];
        
        __block UITextField *textField = cell.tfInput;
        [cell.tfInput.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            if (x.length > 5) {
                textField.text = [x substringToIndex:5];
            }
        }];
        //发送验证码
        
        [cell.captchaBtn bk_addEventHandler:^(id sender) {
            
            [weakSelf sendCaptchaAction:sender];
        } forControlEvents:UIControlEventTouchUpInside];
        
        [cell.tfInput bk_addEventHandler:^(UITextField *sender) {
            sender.placeholder = @"请输入短信验证码";
        } forControlEvents:UIControlEventEditingDidEnd];
        
        cell.tfInput.delegate = self;
        
        return cell;
    } else if(indexPath.row == 3){
        MNDRegisterRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDRegisterRecommendCell"];
        [cell.referrerBtn addTarget:self action:@selector(hideOrShowReferrerAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell.backToLoginBtn addTarget:self action:@selector(toLoginView:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }else {
        
        static NSString *cellIdentifier = @"defaultCell";
        
        MNDRegisterDefaultCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        if (indexPath.row == 2) {
            cell.secretButton.hidden = NO;
        }else {
            cell.secretButton.hidden = YES;
        }
        cell.tfInput.delegate = self;
        
        switch (indexPath.row) {
            case 0: //手机号
            {
                cell.tipLabel.text = @"手机号码";
                cell.tfInput.placeholder = @"请输入手机号";
                RAC(self.registerModel, userPhone) = [cell.tfInput.rac_textSignal takeUntil:cell.rac_prepareForReuseSignal];
                cell.tfInput.keyboardType = UIKeyboardTypeNumberPad;
                __block UITextField *textField = cell.tfInput;
                [cell.tfInput.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
                    if (x.length > 11) {
                        textField.text = [x substringToIndex:11];
                    }
                }];
                
                [cell.tfInput bk_addEventHandler:^(UITextField *sender) {
                    sender.placeholder = @"请输入手机号";
                } forControlEvents:UIControlEventEditingDidEnd];
            }
                break;
            
            case 2: //密码
            {
//                WeakSelf(self);
                cell.tipLabel.text = @"设置密码";
                cell.tfInput.placeholder = @"请设置8-16位数字、字母组合密码";
                [cell.tfInput setSecureTextEntry:YES];
                cell.tfInput.keyboardType = UIKeyboardTypeDefault;

                RAC(self.registerModel, userLoginPassword) = [[RACSignal combineLatest:@[RACObserve(cell, tfInput.text)] reduce:^id (NSString *pwd){
                    return pwd;
                }] takeUntil:cell.rac_prepareForReuseSignal];
                
                __block UITextField *pwdTextField = cell.tfInput;
                [cell.tfInput.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
                    if (x.length > 16) {
                        pwdTextField.text = [x substringToIndex:16];
//                        weakself.registerModel.userLoginPassword = pwdTextField.text;
                    }
                }];
                
//                [cell.tfInput bk_addEventHandler:^(UITextField *sender) {
//                    sender.placeholder = @"密码(8-16位字母数字符号两种及以上组合)";
//                } forControlEvents:UIControlEventEditingDidEnd];
            }
                break;
            case 4: //推荐人
            {
                cell.tipLabel.text = @"推荐码";
                cell.tfInput.placeholder = @"请输入推荐码";
                cell.tfInput.keyboardType = UIKeyboardTypeDefault;
                RAC(self.registerModel, inviteUserCode) = [cell.tfInput.rac_textSignal takeUntil:cell.rac_prepareForReuseSignal];
                
                [cell.tfInput bk_addEventHandler:^(UITextField *sender) {
                    sender.placeholder = @"请输入推荐码";
                } forControlEvents:UIControlEventEditingDidEnd];
            }
                break;
                
            default:
                break;
        }
        
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        return 44;
    }else {
      return 69;
    }
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
//    textField.placeholder = @"";
    return YES;
}

- (void)hideOrShowReferrerAction:(UIButton *)referrerBtn {
    referrerBtn.selected = !referrerBtn.isSelected;
    _showRecommend = !_showRecommend;
    [self.tableView reloadData];
}

- (void)sendCaptchaAction:(UIButton *)captchaBtn {
    
    [self.view endEditing:YES];
    
    if (self.registerModel.userPhone.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号"];
        return;
    }
    
    __block UIButton *captchaButton = captchaBtn;
    
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_REGISTER_SEND_PHONE_CAPTCHA parameters:[MNDSign signedParamWithDict:@{@"user_phone": self.registerModel.userPhone}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"验证码已发送"];
            [captchaButton jk_startTime:30 title:@"重新获取" waitTittle:@"秒后重发"];
        } else {
            NSLog(@"msg: %@", responseModel.msg);
            if ([responseModel.msg isKindOfClass:[NSString class]]) {
                [NetworkProgressHUD showHudMsg:responseModel.msg];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

//注册
- (IBAction)registerAction:(id)sender {
    [self.view endEditing:YES];
    
    if (_registerModel.userPhone.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号"];
        return;
    }
    if (_registerModel.phoneCaptcha.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入验证码"];
        return;
    }
//    if (!_registerModel.userPhone.jk_isMobileNumber) {
//        [NetworkProgressHUD showHudMsg:@"您输入的手机号不正确"];
//        return;
//    }
    
    if (_registerModel.userLoginPassword.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入密码"];
        return;
    }

    NSLog(@"pwd: %@", _registerModel.userLoginPassword);
    NSDictionary *dict = [_registerModel mj_JSONObject];
    NSLog(@"dict: %@", dict);

    [self registerUserWithParam:dict];
    
}
- (IBAction)agreeProtocolAction:(id)sender {
}
- (IBAction)readProtocolDetailAction:(id)sender {
    
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = kRegisterProtocol;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    webVC.title = @"迷你金服平台服务协议";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
    
}
- (IBAction)dismissRegisterAction:(id)sender {
    if (self.isNaviRootVC) {
        
        [self dismissViewControllerAnimated:YES completion:NULL];
        
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Network

- (void)registerUserWithParam:(NSDictionary *)param {
    
    __weak typeof(self) weakSelf = self;
    
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_REGISTER parameters:[MNDSign signedParamWithDict:param] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"注册成功"];
            MNDLoginUserModel *user = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
            //保存数据库
            [MNDLoginUserModel addOrUpdateUser:user];
            
            //保存用户名用于账号管理切换账号
            NSArray *array = [UserDefaultsTool objectForKey:kAccountUserNameArray];
            [weakSelf saveUserNameFromArray:array user:user];
            
            [weakSelf performSelector:@selector(dismissLogin) withObject:nil afterDelay:2.0];
            
            //设置消息推送别名
            [UMessage setAlias:user.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                if (error) {
                    NSLog(@"设置别名失败: %@", error);
                } else {
                    NSLog(@"设置别名成功: %@", responseObj);
                }
            }];
        } else {
            NSDictionary *dic = responseModel.msg;
            [NetworkProgressHUD showHudMsg:dic[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)saveUserNameFromArray:(NSArray *)array user:(MNDLoginUserModel *)user {
    
    NSMutableArray *arrayM = [NSMutableArray arrayWithArray:array];
    
    NSDictionary *dict = @{
                           @"user_name": user.user_name,
                           @"user_photo":user.user_photo,
                           @"user_phone":user.user_phone
                           };
    [arrayM addObject:dict];
    [UserDefaultsTool saveObject:[arrayM copy] forKey:kAccountUserNameArray];
    
    
}

- (void)dismissLogin {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_state" object:@(YES)];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
